package cn.tedu.csmall.cart.webapi.mybatis.interceptor; 
 /*
 @Time: 2023/5/29 11:50
 @Author:GShuai
 @File:MybatisInterceptor.class
 @Software:IntelliJ IDEA
*/

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.springframework.stereotype.Component;

import java.sql.Connection;

/*
 * mybatis拦截器测试
 * */
@Component
@Slf4j
// Mybatis 拦截器配置声明用的注解
// 可以拦截多个jdbc中的对象
@Intercepts({@Signature(
        type = StatementHandler.class,
        method = "prepare",
        args = {Connection.class, Integer.class}
)})
public class MybatisInterceptor implements Interceptor {
    // 执行拦截Mybatis指令的方法
    // invocation:调用,其中包含着运行的指令的信息(包含sql语句指令的)
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        log.info("进入拦截器,准备拦截sql语句");
        // 通过参数invocation,要运行的sql语句对象
        BoundSql boundSql = ((StatementHandler) invocation.getTarget()).getBoundSql();
        // boundSql对象中获得sql语句
        String sql = boundSql.getSql();
        log.info("要运行的sql语句为：{}",sql);
        return invocation.proceed();
    }

}
